from flask import Flask, render_template, flash, redirect, session, request, url_for

app = Flask(__name__)

"""
3.1	模板与模板引擎Jinja2
"""


# @app.route("/index")
# def index():
#     return render_template("index.html")  # 渲染模板文件index.html


"""
3.2.1 模板变量
"""


@app.route("/index")
def index():
    name = "World"
    return render_template("index.html", name=name)


"""
3.2.2 过滤器
"""


# 内置过滤器
@app.route("/filters")
def use_of_filters():
    num = -2.3
    li = [2, 1, 5, 6, 7, 4, 4]
    string = "flask"
    return render_template("filters.html", num=num, li=li, string=string)


# 自定义过滤器
# @app.template_filter()          	# 注册自定义过滤器
# def custom_filters(data):        # 自定义过滤器
#     return data[::-1]


"""
3.2.3 选择结构
"""
# @app.route('/query-score/<int:score>')
# def query_score(score):
#     return render_template('select_struct.html', score=score)


"""
3.2.4 循环结构
"""
# @app.route('/goods')
# def goods():
#     goods_name = ['洗碗机','电饭锅','电烤箱','电磁灶','微波炉']
#     return render_template('loop_struct.html', goods_name=goods_name)


"""
3.3.2	宏的调用
"""
# @app.route('/macro')
# def input_style():
#     return render_template('macro.html')
# @app.route('/macro')
# def input_style():
#     return render_template('macro_called.html')


"""
3.4	消息闪现
"""
app.secret_key = "Your_secret_key&^52@!"  # 设置secret_key


@app.route("/home")
def home_page():
    username = session.get("username")
    # 判断session是否存储username的数据
    if "username" in session:
        return render_template("home_page.html", username=username)
    return redirect(url_for("login"))  # 重定向到login页面


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        # 判断用户输入的用户名是否为admin，密码是否为123
        if request.form["username"] != "admin" or request.form["password"] != "123":
            # 发送登录失败的消息
            flash("用户名或密码错误", category="error")
        else:
            session["username"] = request.form["username"]
            session["password"] = request.form["password"]
            # 发送登录成功的消息
            flash("恭喜您，登录成功", category="info")
            # 登录成功，页面重定向到home_page页面
            return redirect(url_for("home_page"))
    return render_template("login.html")


"""
3.5 静态文件的加载
"""
# @app.route('/static-file')
# def load_staticfile():
#     return render_template('base.html')


"""
3.6	模板继承
"""


@app.route("/child")
def extends_template():
    # return render_template('base.html')
    return render_template("child.html")


if __name__ == "__main__":
    app.run(debug=True)
